package utils;

/**
 * Holds functions for operating on bits.
 * @author Tommi Wiik
 *
 */
public class BitOperator {

	/**
	 * Does xor operation on bytes. Param arrays should be the same length.
	 * @param orig
	 * @param prev
	 * @return
	 */
	public static byte[] doXOR(byte[] orig, byte[] prev) {
		byte[] xorred = new byte[orig.length];
		for (int i=0; i<orig.length*8; i++) {
			xorred=setBit(xorred, i, getBit(orig, i)^getBit(prev, i));
		}
		return xorred;
	}
	
	public static byte[] setBit(byte[] data, int pos, int val) {
    int posByte = pos/8; 
    int posBit = pos%8;
    byte oldByte = data[posByte];
    oldByte = (byte) (((0xFF7F>>posBit) & oldByte) & 0x00FF);
    byte newByte = (byte) ((val<<(8-(posBit+1))) | oldByte);
    data[posByte] = newByte;
    return data;
 }
	
	public static int getBit(byte[] data, int pos) {
    int posByte = pos/8; 
    int posBit = pos%8;
    byte valByte = data[posByte];
    int valInt = valByte>>(8-(posBit+1)) & 0x0001;
    return valInt;
 }
	
	/**
	 * Returns a byte array containing the two's-complement representation of the integer.<br>
	 * The byte array will be in big-endian byte-order with a fixes length of 4
	 * (the least significant byte is in the 4th element).<br>
	 * <br>
	 * <b>Example:</b><br>
	 * <code>intToByteArray(258)</code> will return { 0, 0, 1, 2 },<br>
	 * <code>BigInteger.valueOf(258).toByteArray()</code> returns { 1, 2 }. 
	 * @param integer The integer to be converted.
	 * @return The byte array of length 4.
	 */
	public static byte[] intToByteArray (int integer) {
		int byteNum = (40-Integer.numberOfLeadingZeros (integer < 0 ? ~integer : integer))/8;
		byte[] byteArr = new byte[4];
		
		for (int n=0;n<byteNum;n++)
			byteArr[3-n] = (byte) (integer>>>(n*8));
		
		return (byteArr);
	}
}
